package org.zhaya.sdk.processors;

import cn.hutool.core.collection.CollUtil;
import io.logz.sawmill.Doc;
import io.logz.sawmill.ProcessResult;
import io.logz.sawmill.Processor;
import io.logz.sawmill.annotations.ProcessorProvider;
import io.logz.sawmill.exceptions.ProcessorExecutionException;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@ProcessorProvider(type = "debug", factory = DebugProcessor.Factory.class)
public class DebugProcessor implements Processor {

    public static ThreadLocal<List<Doc>> threadLocal;
    private List<Doc> docList;

    public DebugProcessor() {
        DebugProcessor.threadLocal = new ThreadLocal<>();
    }

    @Override
    public ProcessResult process(Doc doc) {
        try {
            List<Doc> th = threadLocal.get();
            if (CollUtil.isEmpty(th)) {
                docList = new ArrayList<>();
            }
            docList.add(doc);
            threadLocal.set(docList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ProcessResult.failure("failed to process doc to docs for fields", new ProcessorExecutionException("docToDocs", e));
        }
        return ProcessResult.success();
    }

    public static class Factory implements Processor.Factory {

        @Override
        public DebugProcessor create(Map<String, Object> config) {

            Configuration docToDocsConfig = JsonUtils.fromJsonMap(Configuration.class, config);

            return new DebugProcessor();
        }
    }

    @Data
    public static class Configuration implements Processor.Configuration {
        private String path;

    }

}